<script setup>
import { onMounted, ref } from "vue";
import {
  queryStudentPageApi,
  addStudent,
  queryStudentById,
  updateStudent,
  deleteStudentApi,
  handleViolation,
} from "@/api/stu";
import { queryAllClassApi } from "@/api/clazz";
import { dayjs, ElMessage, ElMessageBox } from "element-plus";

const formatDateTime = (data) => {
  return dayjs(data).format("YYYY-MM-DD HH:mm:ss");
};

// 学历选项
const degrees = ref([
  { label: "初中", value: 1 },
  { label: "高中", value: 2 },
  { label: "大专", value: 3 },
  { label: "本科", value: 4 },
  { label: "硕士", value: 5 },
  { label: "博士", value: 6 },
]);

// 性别选项
const genders = ref([
  { label: "男", value: 1 },
  { label: "女", value: 2 },
]);

// 是否院校选项
const isCollegeOptions = ref([
  { label: "是", value: 1 },
  { label: "否", value: 0 },
]);

// 班级列表
const classList = ref([]);

// 表单校验规则
const rules = ref({
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 10, message: "姓名长度在2到10个字符", trigger: "blur" },
  ],
  no: [
    { required: true, message: "请输入学号", trigger: "blur" },
    { len: 10, message: "学号长度必须为10位", trigger: "blur" },
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号格式",
      trigger: "blur",
    },
  ],
  idCard: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    {
      pattern:
        /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/,
      message: "请输入正确的身份证号格式",
      trigger: "blur",
    },
  ],
  clazzId: [{ required: true, message: "请选择班级", trigger: "change" }],
});

// 学员表单数据
const student = ref({
  name: "",
  no: "",
  gender: "",
  phone: "",
  idCard: "",
  isCollege: 1,
  address: "",
  degree: "",
  graduationDate: "",
  clazzId: "",
  violationCount: 0,
  violationScore: 0,
});

// 控制弹窗
const dialogVisible = ref(false);
const dialogTitle = ref("新增学员");

// 违纪相关
const violationDialogVisible = ref(false);
const violationScore = ref(0);
const currentStudentId = ref(null);
const currentStudentName = ref("");

// 表单引用
const formRef = ref();

// 打开对话框
const openDialog = () => {
  formRef.value?.resetFields();
  student.value = {
    name: "",
    no: "",
    gender: "",
    phone: "",
    idCard: "",
    isCollege: 1,
    address: "",
    degree: "",
    graduationDate: "",
    clazzId: "",
    violationCount: 0,
    violationScore: 0,
  };
  dialogVisible.value = true;
  dialogTitle.value = "新增学员";
};

// 显示学员详情
const showStudent = async (id) => {
  const result = await queryStudentById(id);
  student.value = result.data;
  dialogVisible.value = true;
  dialogTitle.value = "修改学员";
};

// 保存学员
const saveStudent = async () => {
  try {
    await formRef.value.validate();

    let res;
    let message;
    if (student.value.id) {
      res = await updateStudent(student.value);
      message = "修改成功";
    } else {
      res = await addStudent(student.value);
      message = "添加成功";
    }

    if (res.code === 1) {
      ElMessage.success(message);
      dialogVisible.value = false;
      search();
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    console.log("表单校验失败", error);
  }
};

// 删除学员
const deleteStudent = async (id) => {
  ElMessageBox.confirm("确定要删除该学员吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    let result = await deleteStudentApi(id);
    if (result.code === 1) {
      ElMessage.success("删除成功");
      search();
    } else {
      ElMessage.error(result.msg);
    }
  });
};

// 批量删除相关
const selectionIds = ref([]);
const handleSelectionChange = (selection) => {
  selectionIds.value = selection.map((item) => item.id);
};

const deleteByIds = () => {
  if (selectionIds.value.length === 0) {
    ElMessage.warning("请至少选择一条记录");
    return;
  }

  ElMessageBox.confirm("确定要删除选中的学员吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    let result = await deleteStudentApi(selectionIds.value);
    if (result.code === 1) {
      ElMessage.success("删除成功");
      search();
    } else {
      ElMessage.error(result.message);
    }
  });
};

// 搜索相关
const searchParams = ref({
  name: "",
  degree: "",
  clazzId: "",
});

const search = async () => {
  const result = await queryStudentPageApi(
    searchParams.value.name,
    searchParams.value.degree,
    searchParams.value.clazzId,
    currentPage.value,
    pageSize.value
  );
  total.value = result.data.total;
  studentList.value = result.data.rows;
};

const clearSearch = () => {
  searchParams.value = {
    name: "",
    degree: "",
    clazzId: "",
  };
  search();
};

// 学员列表数据
const studentList = ref([]);

// 分页配置
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 分页处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  search();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  search();
};

// 违纪相关方法
const openViolationDialog = (id, name) => {
  currentStudentId.value = id;
  currentStudentName.value = name;
  violationScore.value = 0;
  violationDialogVisible.value = true;
};

const submitViolation = async () => {
  if (!violationScore.value || violationScore.value <= 0) {
    ElMessage.warning("请输入有效的扣分分数");
    return;
  }

  try {
    const result = await handleViolation(
      currentStudentId.value,
      violationScore.value
    );
    if (result.code === 1) {
      ElMessage.success("违纪处理成功");
      violationDialogVisible.value = false;
      search(); // 刷新列表
    } else {
      ElMessage.error(result.msg || "处理失败");
    }
  } catch (error) {
    ElMessage.error("处理失败");
    console.error(error);
  }
};

// 初始化数据
onMounted(async () => {
  await search();
  const result = await queryAllClassApi();
  classList.value = result.data;
});
</script>

<template>
  <h1>学员管理</h1>
  <br />

  <!-- 搜索表单 -->
  <el-form :inline="true" :model="searchParams">
    <el-form-item label="姓名">
      <el-input
        v-model="searchParams.name"
        placeholder="请输入学生姓名"
        clearable
      ></el-input>
    </el-form-item>

    <el-form-item label="最高学历">
      <el-select v-model="searchParams.degree" placeholder="请选择" clearable>
        <el-option
          v-for="degree in degrees"
          :key="degree.value"
          :label="degree.label"
          :value="degree.value"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="所属班级">
      <el-select v-model="searchParams.clazzId" placeholder="请选择" clearable>
        <el-option
          v-for="clazz in classList"
          :key="clazz.id"
          :label="clazz.name"
          :value="clazz.id"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button @click="clearSearch">清空</el-button>
    </el-form-item>
  </el-form>

  <!-- 操作按钮 -->
  <el-button type="primary" @click="openDialog"> + 新增学员</el-button>
  <el-button type="danger" @click="deleteByIds"> - 批量删除</el-button>
  <br /><br />

  <!-- 学员表格 -->
  <!-- 学员表格 -->
  <!-- 学员表格 - 占满宽度版本 -->
  <el-table
    :data="studentList"
    border
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
    <el-table-column
      type="selection"
      width="55"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="name"
      label="姓名"
      width="100"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="no"
      label="学号"
      width="120"
      align="center"
    ></el-table-column>
    <el-table-column
      label="班级"
      min-width="180"
      align="center"
      prop="clazzName"
    >
    </el-table-column>
    <el-table-column label="性别" width="80" align="center">
      <template #default="scope">
        {{ scope.row.gender === 1 ? "男" : "女" }}
      </template>
    </el-table-column>
    <el-table-column
      prop="phone"
      label="手机号"
      width="150"
      align="center"
    ></el-table-column>
    <el-table-column label="学历" width="100" align="center">
      <template #default="scope">
        <span v-if="scope.row.degree === 1">初中</span>
        <span v-else-if="scope.row.degree === 2">高中</span>
        <span v-else-if="scope.row.degree === 3">大专</span>
        <span v-else-if="scope.row.degree === 4">本科</span>
        <span v-else-if="scope.row.degree === 5">硕士</span>
        <span v-else-if="scope.row.degree === 6">博士</span>
      </template>
    </el-table-column>
    <el-table-column
      prop="violationCount"
      label="违纪次数"
      width="100"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="violationScore"
      label="违纪扣分"
      width="100"
      align="center"
    ></el-table-column>
    <el-table-column label="修改时间" width="180" align="center">
      <template #default="scope">
        {{ formatDateTime(scope.row.updateTime) }}
      </template>
    </el-table-column>
    <el-table-column label="操作" fixed="right" width="220" align="center">
      <template #default="scope">
        <el-button
          size="small"
          type="primary"
          @click="showStudent(scope.row.id)"
          >编辑
        </el-button>
        <el-button
          size="small"
          type="warning"
          @click="openViolationDialog(scope.row.id, scope.row.name)"
          >违纪
        </el-button>
        <el-button
          size="small"
          type="danger"
          @click="deleteStudent(scope.row.id)"
          >删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <br />

  <!-- 分页 -->
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :page-sizes="[5, 10, 20, 30]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
  ></el-pagination>

  <!-- 新增/修改学员对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
    <el-form :model="student" :rules="rules" ref="formRef" label-width="100px">
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="student.name"
              placeholder="请输入学员姓名"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学号" prop="no">
            <el-input
              v-model="student.no"
              placeholder="请输入10位学号"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select
              v-model="student.gender"
              placeholder="请选择性别"
              style="width: 100%"
            >
              <el-option
                v-for="gender in genders"
                :key="gender.value"
                :label="gender.label"
                :value="gender.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="student.phone"
              placeholder="请输入手机号"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input
              v-model="student.idCard"
              placeholder="请输入身份证号"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否院校" prop="isCollege">
            <el-select
              v-model="student.isCollege"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in isCollegeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="最高学历" prop="degree">
            <el-select
              v-model="student.degree"
              placeholder="请选择学历"
              style="width: 100%"
            >
              <el-option
                v-for="degree in degrees"
                :key="degree.value"
                :label="degree.label"
                :value="degree.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="毕业时间">
            <el-date-picker
              v-model="student.graduationDate"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属班级" prop="clazzId">
            <el-select
              v-model="student.clazzId"
              placeholder="请选择班级"
              style="width: 100%"
            >
              <el-option
                v-for="clazz in classList"
                :key="clazz.id"
                :label="clazz.name"
                :value="clazz.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系地址">
            <el-input
              v-model="student.address"
              placeholder="请输入联系地址"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第六行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="违纪次数">
            <el-input-number
              v-model="student.violationCount"
              :min="0"
              :max="100"
              disabled
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="违纪扣分">
            <el-input-number
              v-model="student.violationScore"
              :min="0"
              :max="100"
              disabled
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStudent">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 违纪扣分对话框 -->
  <el-dialog v-model="violationDialogVisible" title="违纪处理" width="30%">
    <el-form label-width="100px">
      <el-form-item label="学员姓名">
        <el-input v-model="currentStudentName" disabled></el-input>
      </el-form-item>
      <el-form-item label="扣分分数">
        <el-input-number
          v-model="violationScore"
          :min="0"
          :max="100"
          controls-position="right"
        ></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="violationDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitViolation">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-form-item {
  margin-bottom: 20px;
}

.el-button--warning {
  margin: 0 5px;
}
</style>
